package auth

import (
	"github.com/gin-gonic/gin"
	"wskyygyso/api/app/http/controllers/api/v1"
	"wskyygyso/api/app/requests"
	"wskyygyso/api/pkg/auth"
	"wskyygyso/api/pkg/jwt"
	"wskyygyso/api/pkg/response"
)

type LoginController struct {
	v1.BaseApiController
}

func (receiver *LoginController) LoginByPhone(c *gin.Context) {
	request := requests.LoginByPhoneRequest{}
	if !requests.Validate(c, &request, requests.LoginByPhone) {
		return
	}
	userModel, err := auth.LoginByPhone(request.Phone)
	if err != nil {
		response.Error(c, err, "账号不存在或密码错误")
	} else {
		token := jwt.NewJwt().IssueToken(userModel.GetStringId(), userModel.Name)
		response.CreatedJSON(c, gin.H{
			"token": token,
		})
	}
}

func (receiver *LoginController) LoginByPassword(c *gin.Context) {
	request := requests.LoginByPasswordRequest{}
	if !requests.Validate(c, &request, requests.LoginByPassword) {
		return
	}
	userModel, err := auth.Attempt(request.LoginId, request.PassWord)
	if err != nil {
		response.Error(c, err, "账号不存在或密码错误")
	} else {
		token := jwt.NewJwt().IssueToken(userModel.GetStringId(), userModel.Name)
		response.CreatedJSON(c, gin.H{
			"token": token,
		})
	}
}

func (receiver *LoginController) RefreshToken(c *gin.Context) {
	token, err := jwt.NewJwt().Refresh(c)
	if err != nil {
		response.Error(c, err, "令牌刷新失败")
	} else {
		response.CreatedJSON(c, gin.H{
			"token": token,
		})
	}
}
